import express from "express";
import { ErrorRequestHandler } from "express";
import axios from "axios";
import dayjs from "dayjs";
import { join } from "path";
import { getConnection, query } from "./mysql";
const app = express();
const APPID = "wxc316872c88d40c4d";
const SECRET = "777b71603ea14d2e0ba8fba33aaf9f55";
const now = () => dayjs().format("YYYY-MM-DD HH:mm:ss");

app.use(express.json());
app.use(express.urlencoded());
// 开放静态资源
app.use("/static", express.static(join(process.cwd(), "static")));

// 微信授权
app.post("/empower", async (req, res) => {
  const url = `https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&js_code=${req.body.code}&appid=${APPID}&secret=${SECRET}`;
  const r = await axios.get(url);
  if (r.data.openid) {
    const connection = await getConnection();
    // 是否存在用户
    const users = await query(
      connection,
      `select * from user where openid = ?`,
      [r.data.openid]
    );
    if (!users.length) {
      // 用户不存在-创建新用户
      await query(
        connection,
        `insert into user(openid, nickname, avatar, ballLevel, sex) values(?, ?, ?, ?, ?)`,
        [
          r.data.openid,
          "微信用户" + users.length,
          "http://ball.lovedong.work/static/logo.png",
          1,
          "M",
        ]
      );
    }
    const [user] = await query(
      connection,
      `select * from user where openid = ?`,
      [r.data.openid]
    );
    res.json({
      code: 200,
      success: true,
      result: user,
      message: "授权成功",
    });
  } else {
    res.json({
      code: 500,
      success: false,
      result: r.data,
      message: "授权失败",
    });
  }
});

// 404
app.use((req, res) => {
  console.log(now(), "接口不存在", req.method, req.path);
  res.status(404).json({
    code: 404,
    message: "接口不存在",
    result: null,
    success: false,
  });
});

// 错误处理
app.use(((err, req, res, next) => {
  console.log(now(), "错误处理", err.message);
  res.status(500).json({
    code: 500,
    message: err.message,
    result: null,
    success: false,
  });
}) as ErrorRequestHandler);

app.listen(3000, () => console.log("服务已启动: http://127.0.0.1:3000"));
